package com.zhku.shoppingspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhku.shoppingspringboot.pojo.entity.Categories;
import com.zhku.shoppingspringboot.mapper.CategoriesMapper;
import com.zhku.shoppingspringboot.pojo.entity.Goods;
import com.zhku.shoppingspringboot.pojo.vo.CategoryVO;
import com.zhku.shoppingspringboot.pojo.vo.GoodsVO;
import com.zhku.shoppingspringboot.service.ICategoriesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jieeee
 * @since 2025-01-03
 */
@Service
public class CategoriesServiceImpl extends ServiceImpl<CategoriesMapper, Categories> implements ICategoriesService {

    @Override
    public List<CategoryVO> getAllCategory() {
        //获取全部的列表
        List<Categories> list = this.list();
        //获取一级列表
        List<CategoryVO> categoryVOList = list.stream().filter(item -> item.getLayer() == 1)
                .map(item -> new CategoryVO().
                        setId(item.getId()).setName(item.getName())
                        .setPicture(item.getPicture())).collect(Collectors.toList());
     //根据一级列表的id获取二级列表
        for (int i = 0; i < categoryVOList.size(); i++) {
            CategoryVO categoryVO = categoryVOList.get(i);
            Integer parentId = categoryVO.getId();
            List<CategoryVO> child = list.stream().filter(item -> item.getLayer() == 2 && item.getParentId() == parentId)
                    .map(item -> new CategoryVO().
                            setId(item.getId()).setName(item.getName())
                            .setPicture(item.getPicture())).collect(Collectors.toList());
            categoryVO.setChildren(child);
            categoryVOList.set(i,categoryVO);
        }
        return categoryVOList;
    }

    @Override
    public CategoryVO getSecondaryCategory(Integer id) {
            Categories byId = this.getById(id);
//            获取一级
            CategoryVO categoryVO =  new CategoryVO().
                setId(byId.getId()).setName(byId.getName())
                .setPicture(byId.getPicture());
//获取二级
        LambdaQueryWrapper<Categories> lambdaQueryWrapper=new LambdaQueryWrapper<Categories>()
                .like(Categories::getParentId,id);
        List<Categories> list = this.list();
        List<CategoryVO> categoryVOList = list.stream().map(item -> new CategoryVO().setId(item.getId())
                .setName(item.getName()).setPicture(item.getPicture())).collect(Collectors.toList());
        CategoryVO result = categoryVO.setChildren(categoryVOList);

        return result;
    }


}
